import {_decorator, Component, Node, Vec3, ParticleSystem} from 'cc';

const {ccclass, property} = _decorator;

/**
 * 测试武器飞行脚本
 */
@ccclass('TestController')
export class TestController extends Component {
    @property
    public speed: number = 10;

    @property
    public range: number = 30;

    @property([Node])
    public targetNodes: Node[] = [];

    private originPositions: any[] = [];
    private arriveEnds: number[] = [];

    start() {
        this.originPositions = [];
        this.arriveEnds = [];

        this.targetNodes.forEach((ndItem: Node) => {
            this.originPositions.push(ndItem.worldPosition.clone());
        })
    }

    update(deltaTime: number) {
        if (this.targetNodes.length) {
            for (let idx = 0; idx < this.targetNodes.length; idx++) {
                const ndItem = this.targetNodes[idx];
                let pos = ndItem.worldPosition.clone()
                if (pos.length() >= this.range) {
                    if (this.arriveEnds.indexOf(idx) === -1) {
                        this.arriveEnds.push(idx);
                    }

                    if (this.arriveEnds.length >= this.targetNodes.length) {
                        this.resetAllPosition();
                        break;
                    }
                } else {
                    ndItem.translate(new Vec3(0, 0, -deltaTime * this.speed), Node.NodeSpace.LOCAL);
                }
            }
        }
    }

    private resetAllPosition() {
        this.targetNodes.forEach((ndItem: Node, idx: number) => {
            ndItem.setWorldPosition(this.originPositions[idx]);

            //清除拖尾特效残留
            let arrParticle: ParticleSystem[] = ndItem.getComponentsInChildren(ParticleSystem);
            arrParticle.forEach((item: ParticleSystem) => {
                item.simulationSpeed = 1;
                item?.clear();
                item?.stop();
                item?.play();
            })
        })

        this.arriveEnds = [];
    }
}